import React, { useState, useCallback } from 'react';
import { 
  Card, 
  Upload, 
  Button, 
  Form, 
  Input, 
  Select, 
  Space, 
  Progress, 
  message,
  Row,
  Col,
  Tag,
  Typography
} from 'antd';
import { 
  InboxOutlined, 
  UploadOutlined, 
  PlayCircleOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined
} from '@ant-design/icons';
import { useElectronAPI } from '../hooks/useElectronAPI';

const { Dragger } = Upload;
const { TextArea } = Input;
const { Option } = Select;
const { Text: AntText } = Typography;

interface UploadTask {
  id: string;
  fileName: string;
  status: string;
  progress: number;
  platforms: string[];
  platformResults: any;
}

const UploadPage: React.FC = () => {
  const [form] = Form.useForm();
  const [uploading, setUploading] = useState(false);
  const [fileList, setFileList] = useState<any[]>([]);
  const [selectedPlatforms, setSelectedPlatforms] = useState<string[]>([]);
  const [currentTask, setCurrentTask] = useState<UploadTask | null>(null);
  
  const electronAPI = useElectronAPI();

  const [platforms] = useState([
    { id: 'douyin', name: '抖音', icon: '🎵' },
    { id: 'bilibili', name: '哔哩哔哩', icon: '📺' },
    { id: 'xiaohongshu', name: '小红书', icon: '📒' }
  ]);

  const handleFileChange = (info: any) => {
    setFileList(info.fileList);
  };

  const beforeUpload = (file: File) => {
    const isVideo = file.type.startsWith('video/');
    const isLt2G = file.size / 1024 / 1024 / 1024 < 2;
    
    if (!isVideo) {
      message.error('只能上传视频文件!');
      return false;
    }
    if (!isLt2G) {
      message.error('视频大小不能超过2GB!');
      return false;
    }
    return true;
  };

  const handleUpload = async () => {
    if (fileList.length === 0) {
      message.error('请选择视频文件');
      return;
    }

    if (selectedPlatforms.length === 0) {
      message.error('请选择发布平台');
      return;
    }

    try {
      setUploading(true);
      const values = await form.validateFields();
      
      const file = fileList[0].originFileObj;
      
      // 创建上传任务
      const task: UploadTask = {
        id: Date.now().toString(),
        fileName: file.name,
        status: 'uploading',
        progress: 0,
        platforms: selectedPlatforms,
        platformResults: {}
      };
      
      setCurrentTask(task);

      // 模拟上传过程
      for (let i = 0; i <= 100; i += 10) {
        await new Promise(resolve => setTimeout(resolve, 500));
        setCurrentTask(prev => prev ? { ...prev, progress: i } : null);
      }

      // 发布到选中的平台
      await publishToPlatforms(task.id, selectedPlatforms, values);
      
    } catch (error) {
      message.error('上传失败: ' + (error as Error).message);
    } finally {
      setUploading(false);
    }
  };

  const publishToPlatforms = async (taskId: string, platforms: string[], metadata: any) => {
    try {
      setCurrentTask(prev => prev ? { ...prev, status: 'publishing' } : null);
      
      // 模拟发布到各个平台
      for (const platform of platforms) {
        await new Promise(resolve => setTimeout(resolve, 2000));
        
        setCurrentTask(prev => {
          if (!prev) return null;
          return {
            ...prev,
            platformResults: {
              ...prev.platformResults,
              [platform]: {
                status: 'success',
                url: `https://${platform}.com/video/${Date.now()}`
              }
            }
          };
        });
      }

      message.success('发布完成！');
      setCurrentTask(prev => prev ? { ...prev, status: 'completed' } : null);
      
    } catch (error) {
      message.error('发布失败: ' + (error as Error).message);
    }
  };

  const handlePlatformChange = (platforms: string[]) => {
    setSelectedPlatforms(platforms);
  };

  const uploadProps = {
    multiple: false,
    accept: 'video/*',
    beforeUpload,
    onChange: handleFileChange,
    fileList,
    showUploadList: {
      showPreviewIcon: false,
      showRemoveIcon: true,
    }
  };

  return (
    <div style={{ padding: '24px' }}>
      <Row gutter={24}>
        <Col span={16}>
          <Card title="上传视频">
            <Dragger {...uploadProps}>
              <p className="ant-upload-drag-icon">
                <InboxOutlined style={{ fontSize: 48, color: '#1890ff' }} />
              </p>
              <p className="ant-upload-text">点击或拖拽视频文件到此处上传</p>
              <p className="ant-upload-hint">
                支持 MP4、AVI、MOV、MKV、FLV 格式，单个文件不超过 2GB
              </p>
            </Dragger>

            <Form form={form} layout="vertical" style={{ marginTop: 24 }}>
              <Form.Item
                label="视频标题"
                name="title"
                rules={[{ required: true, message: '请输入视频标题' }]}
              >
                <Input placeholder="请输入吸引人的标题" maxLength={100} />
              </Form.Item>

              <Form.Item
                label="视频描述"
                name="description"
                rules={[{ required: true, message: '请输入视频描述' }]}
              >
                <TextArea 
                  rows={4} 
                  placeholder="详细描述你的视频内容..."
                  maxLength={500}
                  showCount
                />
              </Form.Item>

              <Form.Item
                label="标签"
                name="tags"
                rules={[{ required: true, message: '请添加至少一个标签' }]}
              >
                <Select
                  mode="tags"
                  placeholder="输入标签后按回车"
                  tokenSeparators={[',']}
                />
              </Form.Item>

              <Form.Item
                label="发布平台"
                name="platforms"
                rules={[{ required: true, message: '请选择发布平台' }]}
              >
                <Select
                  mode="multiple"
                  placeholder="选择要发布的平台"
                  onChange={handlePlatformChange}
                >
                  {platforms.map(platform => (
                    <Option key={platform.id} value={platform.id}>
                      <span>{platform.icon}</span> {platform.name}
                    </Option>
                  ))}
                </Select>
              </Form.Item>

              <Form.Item>
                <Button 
                  type="primary" 
                  onClick={handleUpload}
                  loading={uploading}
                  icon={<UploadOutlined />}
                  size="large"
                  block
                >
                  {uploading ? '上传中...' : '开始上传并发布'}
                </Button>
              </Form.Item>
            </Form>
          </Card>
        </Col>

        <Col span={8}>
          <Card title="上传进度">
            {currentTask ? (
              <Space direction="vertical" style={{ width: '100%' }}>
                <div>
                  <AntText strong>{currentTask.fileName}</AntText>
                </div>
                
                <Progress 
                  percent={currentTask.progress} 
                  status={currentTask.status === 'failed' ? 'exception' : 'normal'}
                />

                <div>
                  <AntText>状态：</AntText>
                  <Tag color={
                    currentTask.status === 'completed' ? 'success' :
                    currentTask.status === 'failed' ? 'error' :
                    currentTask.status === 'uploading' ? 'processing' :
                    'default'
                  }>
                    {currentTask.status}
                  </Tag>
                </div>

                {Object.entries(currentTask.platformResults).map(([platform, result]: [string, any]) => (
                  <div key={platform}>
                    <AntText>{platform}：</AntText>
                    {result.status === 'success' ? (
                      <CheckCircleOutlined style={{ color: '#52c41a' }} />
                    ) : result.status === 'failed' ? (
                      <CloseCircleOutlined style={{ color: '#ff4d4f' }} />
                    ) : (
                      <PlayCircleOutlined style={{ color: '#1890ff' }} />
                    )}
                    {result.url && (
                      <a href={result.url} target="_blank" rel="noopener noreferrer" style={{ marginLeft: 8 }}>
                        查看
                      </a>
                    )}
                  </div>
                ))}
              </Space>
            ) : (
              <AntText type="secondary">暂无上传任务</AntText>
            )}
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default UploadPage;
